/*
 * @Author: zhangyang
 * @Date: 2022-02-28 17:19:35
 * @LastEditTime: 2022-08-27 16:32:47
 * @Description: vite 配置文件
 */
import { fileURLToPath, URL } from 'url';

import { defineConfig, loadEnv } from 'vite';
import type { ConfigEnv, UserConfigExport } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import legacy from '@vitejs/plugin-legacy';
import Unocss from 'unocss/vite';
// 自动导入
import AutoImport from 'unplugin-auto-import/vite';
import AutoComopnents from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
import AutoIcons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
// 自动路由及布局
import Pages from 'vite-plugin-pages';
import Layouts from 'vite-plugin-vue-layouts';
// 自动处理 optimizeDeps 缓存
import OptimizationPersist from 'vite-plugin-optimize-persist';
import PkgConfig from 'vite-plugin-package-config';
//  获取所有需要自动导入的自定义方法的名称
import * as YoungMethods from './src/young-common-expose';

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const root = process.cwd();
  const viteEnv = loadEnv(mode, root);
  console.log("🚀 ~ file: vite.config.ts ~ line 36 ~ viteEnv", viteEnv);
  return defineConfig({
    plugins: [
      vue(),
      vueJsx(),
      Pages({
        extensions: ['vue', 'tsx'],
        dirs: 'src/views',
        exclude: ['**/components/*.{vue,tsx}', '_*']
      }),
      Layouts({ defaultLayout: 'default' }),
      AutoComopnents({
        dirs: ['src/components'],
        dts: './src/auto-components.d.ts',
        extensions: ['vue', 'tsx'],
        resolvers: [
          NaiveUiResolver(),
          IconsResolver({ componentPrefix: 'icon' }),
        ]
      }),
      AutoImport({
        dts: './src/auto-imports.d.ts',
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia', {
          '@/young-common-expose': Object.keys(YoungMethods)
        }],
      }),
      AutoIcons(),
      Unocss(),
      PkgConfig(),
      OptimizationPersist(),
      // 不生成同名 polyfill 文件，打包速度翻倍
      // 如果出现兼容问题，可以删除此配置
      legacy({ renderLegacyChunks: false })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: true,
      proxy: {
        [viteEnv.VITE_BASE_HTTP]: viteEnv.VITE_DEV_ADDRESS
      }
    },
    test: {
      globals: true,
      environment: 'jsdom',
      transformMode: {
        web: [/.[tj]sx$/]
      }
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        }
      }
    }
  });
}
